import { Router, Request, DependencyContainer } from "@sker/core";
import { watchAddon } from '@sker/core'
import { exec, ExecOptions } from "child_process";
import { join } from 'path'
declare const injector: DependencyContainer;
export async function useBuild(isWatch: boolean = false) {
    const req = injector.resolve(Request)
    const router: Router = Reflect.get(req, 'router')
    const { scope, addon, root } = router;
    await awaitExec('pnpm run tsc', { cwd: join(root, `addons/@${scope}/${addon}`) })
    await watchAddon(scope, addon, isWatch)
    return true;
}

export const awaitExec = async (command: string, options: ExecOptions = {}) => {
    return new Promise<void>((resolve, reject) => {
        const root = process.cwd();
        const npmInstall = exec(command, { cwd: root, ...options })
        npmInstall.on('close', () => resolve())
        npmInstall.on('error', (e) => reject(e))
        npmInstall.stdout.pipe(process.stdout)
    })
}
